import showTost from '@/components/toast/index.js'
import { createFetch } from '@vueuse/core'
import { destr } from 'destr'

function objToSearch(params) {
  if(!params) return
  let str = ''
  if(Object.keys(params).length) {
    for(const k in params) {
      str += `${k}=${params[k]}&`
    }
    str = str.slice(0, str.length - 1)
  }
  return str
}

export const useApi = createFetch({
  baseUrl: import.meta.env.VITE_API_BASE_URL || '/admin',
  fetchOptions: {
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
  },
  options: {
    refetch: true,
    async beforeFetch({ options }) {
      const accessToken = useCookie('accessToken').value
      if (accessToken) {
        options.headers = {
          ...options.headers,
          Authorization: `${accessToken}`,
        }
      }
      
      return { options }
    },
    afterFetch(ctx) {
      const { data, response } = ctx
      // Parse data if it's JSON
      let parsedData = null
      try {
        parsedData = destr(data)
        if(parsedData.status!==200 && !parsedData.key && !parsedData.code){  
          if(parsedData.status==101 || parsedData.status==102){
            useCookie('accessToken').value = null
            location.href = '/login'
          }else{
            //toast提示报错
            showTost(parsedData.msg, { duration: 3000, type: 'error' })
          }
        }else{
          return { data: parsedData, response }
        }
      }
      catch (error) {
        console.error(error)
      }
      
      return { data: parsedData, response }
    },
  },
})

export const newUseApi = createFetch({
  baseUrl: import.meta.env.VITE_API_BASE_URL || '/admin',
  fetchOptions: {
    headers: {
      Accept: 'application/json',
    },
  },
  options: {
    refetch: true,
    async beforeFetch({ options }) {
      const accessToken = useCookie('accessToken').value
      if (accessToken) {
        options.headers = {
          ...options.headers,
          Authorization: `${accessToken}`,
        }
      }

      return { options }
    },
    afterFetch(ctx) {
      const { data, response } = ctx

      // Parse data if it's JSON
      let parsedData = null
      try {
        parsedData = destr(data)
        console.log(parsedData)
        console.log(parsedData.status!==200 && !parsedData.key && !parsedData.code)
        if(parsedData.status!==200 && !parsedData.key && !parsedData.code){
          if(parsedData.status==101 || parsedData.status==102){
            useCookie('accessToken').value = null
            location.href = '/login'
          }else{

            //toast提示报错
            showTost(parsedData.msg, { duration: 3000, type: 'error' })
            return ''
          }
        }else{
          return { data: parsedData.data, response }
        }
      }
      catch (error) {
        console.error(error)
      }


    },
  },
})


export const  postApi =  (url, params)=>{
  return new Promise(async (resolve, reject)=>{
    const {data} = await useApi(url).post(params)
    if(data.value.code!==200){
      reject(data.value.msg)
    }else{
      resolve(data.value)
    }
  })
}

export const getApi = (url, params) => {
  return new Promise(async (resolve, reject) => {
    console.log(params, 'parmamd');
    
    if(params && objToSearch(params)) url = `${url}?${objToSearch(params)}`
    const {data} = await useApi(url)
    if(data.value.code != 200){
      reject(data.value?.msg || `请求接口${url}报错`)
    }else{
      resolve(data.value)
    }
  })
}
